//
//  WBKeyboardToolbar.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/18.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

fileprivate let baseTag = 888

protocol WBKeyboardToolbarDelegate: NSObjectProtocol {
    func changeKeyboard(index: Int)
}

class WBKeyboardToolbar: UIStackView {
    /// 当前选中的button的index
    var index: Int = 0 {
        didSet {
            let tag = baseTag + index
            let button = self.viewWithTag(tag) as! UIButton
            //先把之前的选中的button还原
            selectedButton?.isSelected = false
            //重新设置selectedButton
            selectedButton = button
            selectedButton?.isSelected = true
        }
    }
    
    /// 代理属性
    weak var delegate: WBKeyboardToolbarDelegate?
    
    //当前选中的button
    var selectedButton: UIButton?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //当子视图水平分布
        axis = .horizontal
        //等距平均分布
        distribution = .fillEqually
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension WBKeyboardToolbar {
    func setupUI () {
        //button的参数的字典数组
        let dicArr: [[String: String]] = [["bgImage": "compose_emotion_table_left", "text":"最近"], ["bgImage": "compose_emotion_table_mid", "text":"默认"], ["bgImage": "compose_emotion_table_mid", "text":"emoji"], ["bgImage": "compose_emotion_table_right", "text":"浪小花"]]
        
        //遍历字典数组创建button
        for (index,dic) in dicArr.enumerated() {
            let imageName = dic["bgImage"]! + "_normal"
            let simageName = dic["bgImage"]! + "_selected"
            let text = dic["text"]!
            
            let button = UIButton()
            //设置选中状态的背景图片
            button.setBackgroundImage(UIImage(named: imageName), for: .normal)
            button.setBackgroundImage(UIImage(named: simageName), for: .selected)
            button.setTitle(text, for: .normal)
            //设置选中状态的文字颜色
            button.setTitleColor(UIColor.darkGray, for: .selected)
            button.setTitleColor(UIColor.white, for: .normal)
            button.tag = index + baseTag
            
            //添加事件
            button.addTarget(self, action: #selector(changeEmotion(button:)), for: .touchUpInside)

            //添加子视图
            addArrangedSubview(button)
            
            //第一个button默认是选中状态
            if index == 0 {
                button.isSelected = true
                selectedButton = button
            }
        }
    }
}

// MARK: - 事件处理
extension WBKeyboardToolbar {
    @objc func changeEmotion(button: UIButton) {
        let index = button.tag - baseTag
        //先把之前的选中的button还原
        selectedButton?.isSelected = false
        //重新设置selectedButton
        selectedButton = button
        selectedButton?.isSelected = true
        
        //让代理切换表情键盘的表情类型
        delegate?.changeKeyboard(index: index)
    }
}

